<!--智慧工地登录页-->
<template>
</template>

<script>
  import getParameterMap from '../tool/getParameterMap'
  export default {
    name: '',
    data () {
      return {
        username: '',
        password: '',
        phone: '',
        phoneCode: '获取验证码',
        checkCode: '',
        count: 60,
        captcha: '',
        isDisabled: false,
        dialogShow: true,
        loginTitle: '登录出错 ',
        loginTip: '短信登录',
        InterVal: null,
        isFirstQuery: false,
        dialogConfirm: '',
        ticket: '',
        coId: '',
        pjId: '',
        src: '',
        resolve: null,
        companyInfo: {},
        type: 1, // 进入的是企业层还是项目层 1： 企业层 2：项目层
        roleId: 1,
        project: [],
        roleType: {
          admin: false, // 部门管理员
          superAdmin: false, // 超级管理员
          advancedAdmin: false // 企业管理员
        },
        memberId: '',
        companyAndemployee: {}
      }
    },
    mounted () {
      let query = getParameterMap()
      if (query) {
        this.ticket = query.ticket
        this.ssoFinished()
      }
    },
    methods: {
      async ssoFinished () {
        await this.ticketVerify()
        await this.findCompanyInfo()
        await this.domain()
        if (this.type === 1) {
          // 获取企业角色
          await this.findRoleByMid()
        } else {
          // 获取项目角色
          await this.findProjectRoleByMid()
        }
        await this.getUserDepartmentType()
        await this.userInfo()
        if (this.companyAndemployee.departmentType === null || this.companyAndemployee.departmentType === '') {
          this.$message.warning('没有权限')
          return
        }
        if (this.companyAndemployee.departmentType !== 13 || this.roleId === 3 || this.roleId === 4) {
          // this.$router.push({name: 'videoMap'})
          location.replace(`${window.location.origin}/#/map`)
        } else {
          await this.findProjectList()
          if (this.project.length > 0) {
            location.replace(`${window.location.origin}/#/video/project?pjId=${this.project[0].projectId}&name=${this.project[0].projectTitle}`)
            // this.$router.push({name: 'videoProject', query: {pjId: this.project[0].projectId, name: this.project[0].projectTitle}})
          } else {
            this.$message.warning('您所在的项目没有关联设备')
          }
        }
      },
      // 获取ticket
      ticketVerify () {
        return new Promise(resolve => {
          this.$axios.get(`${this.$site.passportServer}/common/ticketVerify.htm`, {
            params: {
              ticket: this.ticket,
              returnUrl: `${window.location.origin}/ticket.html`,
              type: 'bgy'
            }
          }).then(res => {
            this.isFirstQuery = false
            if (res.data.errorMsg) {
              this.$message.error(res.data.errorMsg)
              setInterval(() => {
                location.replace(`${window.location.origin}/#/login`)
              }, 1000)
            } else {
              resolve()
            }
          }, err => {
            const {status} = err.request
            let errText = '请先登入'
            switch (status) {
              case 502:
                errText = '服务器开小差了，请稍候...'
                break
              case 504:
                errText = '服务器开小差了，请稍候...'
                break
            }
            this.isFirstQuery = false
            this.$message.error(errText)
          })
        })
      },
      // 获取用户状态
      findCompanyInfo () {
        /**
         * joinStatus 用户状态
         * 1 加入企业
         * 2 申请中
         * 3 未加入企业 也没有申请中的企业
         * null 协作用户 如工人
         * */
        return new Promise(resolve => {
          this.$axios({
            method: 'post',
            url: `${this.$site.companyServer}/common/findCompanyInfo.htm`
          }).then(res => {
            if (res.data.errorMsg) {
              this.$message.error(res.data.errorMsg)
            } else {
              const {company, employee} = res.data
              const joinStatus = company.join_status
              if (joinStatus === 1 || !joinStatus) {
                this.companyAndemployee = {...employee, ...company}
                resolve()
              }
            }
          })
        })
      },
      // 得到当前的项目或者企业
      domain () {
        return new Promise(resolve => {
          this.$axios({
            method: 'post',
            url: `${this.$site.homeServer}/api/nav/findDomain.htm?type=${this.type}&companyId=${this.coId}`
          }).then(res => {
            if (res.data.errorMsg) {
              this.$message.error(res.data.errorMsg)
            } else {
              this.companyInfo = res.data.data
              resolve()
            }
          })
        })
      },
      // 获取管理信息
      findRoleByMid () {
        return new Promise(resolve => {
          this.$axios({
            method: 'post',
            url: `${this.$site.companyServer}/front/findRoleByMid.htm`
          }).then(res => {
            if (res.data.errorMsg) {
              this.$message.error(res.data.errorMsg)
            } else {
              this.roleId = res.data.roleId
              this.setUserRole(res.data.roleId)
              resolve()
            }
          })
        })
      },
      // 获取项目管理信息
      findProjectRoleByMid () {
        return new Promise(resolve => {
          this.$axios({
            method: 'post',
            url: `${this.$site.projectServer}/front/person/findProjectManInfo.htm`
          }).then(res => {
            if (res.data.errorMsg) {
              this.$message.error(res.data.errorMsg)
            } else {
              if (res.data.man) {
                this.roleId = res.data.man.type
                this.setUserProjectRole(this.roleId)
              } else {
                this.roleType.admin = false
                this.roleType.advancedAdmin = false
                this.roleType.superAdmin = false
              }
              resolve()
            }
          })
        })
      },
      // 获取用户信息
      userInfo () {
        return new Promise(resolve => {
          this.$axios({
            method: 'get',
            url: `${this.$site.passportServer}/member/userInfo.htm`
          }).then(res => {
            if (res.data.errorMsg) {
              this.$message.error(res.data.errorMsg)
            } else {
              const user = res.data.info
              Object.assign(user, {type: this.type})
              Object.assign(user, {coId: this.companyAndemployee.company_id})
              Object.assign(user, {pjId: this.companyInfo.projectId})
              Object.assign(user, {coLogo: this.companyAndemployee.logoUrl})
              Object.assign(user, {departmentName: this.companyAndemployee.departmentName})
              Object.assign(user, {departmentType: this.companyAndemployee.departmentType})
              Object.assign(user, {departmentId: this.companyAndemployee.departmentId})
              Object.assign(user, {belong_dep_code: this.companyAndemployee.belong_dep_code})
              Object.assign(user, {pjName: this.companyInfo.projectTitle})
              Object.assign(user, {roleId: this.roleId})
              Object.assign(user, {cono: this.companyInfo.cono})
              Object.assign(user, {coName: this.companyInfo.coname})
              Object.assign(user, {admin: this.roleType.admin}) // 部门管理员
              Object.assign(user, {superAdmin: this.roleType.superAdmin}) // 超级管理员
              Object.assign(user, {advancedAdmin: this.roleType.advancedAdmin}) // 企业管理员
              this.convertUserInfoMLogo(user)
                .then(res => {
                  Object.assign(user, {mLogo: res})
                })
                .catch(() => {
                  Object.assign(user, {mLogo: ''})
                })
                .finally(() => {
                  this.$setCookie('currentUser', JSON.stringify(user), {expires: 14, domain: this.$site.domain})
                  this.$store.commit('editCurrentUser', user)
                  resolve()
                })
            }
          })
        })
      },
      findProjectList () {
        return new Promise(resolve => {
          const data = {
            'mid': this.companyAndemployee.mid,
            'coId': this.companyAndemployee.company_id,
            'departmentId': this.companyAndemployee.departmentId
          }
          this.$axios({
            method: 'post',
            url: `${this.$site.videoServer}/api/hikvision8700/getProjectPassCheckByAllVideos`,
            data: this.$qs.stringify(data)
          }).then(res => {
            this.project = res.data.data
            resolve()
          })
        })
      },
      getUserDepartmentType () {
        /**
         * 根据部门ID 获取部门类型
         * @param departmentId  部门id
         * @return  部门类型
         */
        return new Promise(resolve => {
          const data = {
            departmentId: this.companyAndemployee.departmentId
          }
          this.$axios({
            method: 'post',
            url: `${this.$site.videoServer}/api/hikvision8700/getDeptType`,
            data: this.$qs.stringify(data)
          }).then(res => {
            if (res.data.success) {
              this.companyAndemployee.departmentType = res.data.data.deptType
              resolve()
            } else {
              this.$message.error('获取部门类型出错')
            }
          })
        })
      },
      convertUserInfoMLogo (user) { // 将mLogo由uuid转为url
        return new Promise((resolve, reject) => {
          const mLogo = user.mLogo
          if (!mLogo) {
            reject()
            return false
          }
          this.$axios({
            method: 'post',
            url: `${this.$site.homeServer}/common/fileDownloadUrl.htm`,
            data: this.$qs.stringify({
              'fileUuid': mLogo,
              'th': 1
            })
          }).then(res => {
            if (res.data.errorMsg) {
              // this.$message.error(res.data.errorMsg)
              reject()
            } else {
              this.$store.commit('editCurrentUser', {mLogo: res.data})
              resolve(res.data)
            }
          })
        })
      },
      // 手机登录
      phoneLogin () {
        this.$vaildation(this).then(() => {
          let data = {
            'loginForm.mobile': this.phone,
            'loginForm.code': this.captcha
          }
          this.$axios({
            method: 'post',
            url: `${this.$site.passportServer}/front/login_by_phone.htm`,
            data: this.$qs.stringify(data, {indices: false})
          }).then(res => {
            if (res.data.errorMsg) {
              this.$message.error(res.data.errorMsg)
            } else {
              this.$router.push({name: 'msgcenter'})
            }
          })
        })
      },
      // 获取短信验证码
      sendMessage (type) {
        if (!this.phone) {
          this.$message.error('请输入手机号')
          return
        }
        let data = {
          'loginForm.mobile': this.phone,
          'loginForm.type': type
        }
        this.$axios({
          method: 'post',
          url: `${this.$site.passportServer}/front/login/login_code_send.htm`,
          data: this.$qs.stringify(data, {indices: false})
        }).then(res => {
          if (res.data.errorMsg) {
            this.$message.error(res.data.errorMsg)
          } else {
            this.$message.success(res.data.msg)
            this.isDisabled = true
            this.phoneCode = `${this.count}秒后再获取`
            this.setCurCount()
          }
        })
      },
      setCurCount () {
        this.InterVal = setInterval(() => {
          this.setRemainTime()
        }, 1000)
      },
      setRemainTime () {
        if (this.count === 0) {
          clearInterval(this.InterVal)
          this.phoneCode = '重新发送验证码'
          this.isDisabled = false
        } else {
          this.count--
          this.phoneCode = `${this.count}秒后再获取`
        }
      },
      setUserProjectRole (roleId) {
        switch (roleId) {
          case 1 : // 项目管理员
            this.roleType.admin = true
            this.roleType.advancedAdmin = true
            this.roleType.superAdmin = false
            break
          case 2 : // 项目成员
            this.roleType.admin = false
            this.roleType.advancedAdmin = false
            this.roleType.superAdmin = false
            break
          case 4 : // 项目负责人
            this.roleType.admin = true
            this.roleType.advancedAdmin = true
            this.roleType.superAdmin = true
            break
        }
      },
      setUserRole (roleId) {
        switch (roleId) {
          case 1 :
            break
          case 2 : // 部门管理员
            this.roleType.admin = true
            this.roleType.advancedAdmin = false
            this.roleType.superAdmin = false
            break
          case 3 : // 超级管理员
            this.roleType.admin = true
            this.roleType.advancedAdmin = true
            this.roleType.superAdmin = true
            break
          case 4 : // 企业管理员
            this.roleType.admin = true
            this.roleType.advancedAdmin = true
            this.roleType.superAdmin = false
            break
        }
      }
    }
  }
</script>
